package captcha

import (
	"github.com/vueadmin/app/admin/internal/svc"
	"math/rand"
	"time"

	"github.com/mojocn/base64Captcha"
)

type configJsonBody struct {
	Id            string
	CaptchaType   string
	VerifyValue   string
	DriverAudio   *base64Captcha.DriverAudio
	DriverString  *base64Captcha.DriverString
	DriverChinese *base64Captcha.DriverChinese
	DriverMath    *base64Captcha.DriverMath
	DriverDigit   *base64Captcha.DriverDigit
}

var store base64Captcha.Store

func init() {
	rand.Seed(time.Now().Unix())
}

// 获取验证码
func Generate(svcCtx *svc.ServiceContext) map[string]interface{} {
	param := configJsonBody{
		Id:          "",
		CaptchaType: "digit",
		VerifyValue: "",
		DriverDigit: &base64Captcha.DriverDigit{
			Height:   80,
			Width:    240,
			Length:   4,
			MaxSkew:  0.1,
			DotCount: 80,
		},
	}
	var driver base64Captcha.Driver

	switch param.CaptchaType {
	case "audio":
		driver = param.DriverAudio
	case "string":
		driver = param.DriverString.ConvertFonts()
	case "math":
		driver = param.DriverMath.ConvertFonts()
	case "chinese":
		driver = param.DriverChinese.ConvertFonts()
	default:
		driver = param.DriverDigit
	}

	store = RedisStore{svcCtx: svcCtx}
	c := base64Captcha.NewCaptcha(driver, store)

	id, base64, _, _ := c.Generate()

	data := make(map[string]interface{})
	data["key"] = id
	data["base64"] = base64

	return data
}

// 验证
func Verify(svcCtx *svc.ServiceContext, id string, VerifyValue string) (res bool) {
	param := configJsonBody{
		Id:          id,
		CaptchaType: "digit",
		VerifyValue: VerifyValue,
		DriverDigit: &base64Captcha.DriverDigit{
			Height:   80,
			Width:    240,
			Length:   4,
			MaxSkew:  0.7,
			DotCount: 80,
		},
	}
	store = RedisStore{svcCtx: svcCtx}
	return store.Verify(param.Id, param.VerifyValue, true)
}
